﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
#if NetFx40
using System.Diagnostics.Contracts;
#endif
using System.IO;
using System.Reflection;
namespace XYZShell.Helper
{
    public static  class StringHelper
    {
        public static bool IsNumberic(this string s)
        {
			throw new NotImplementedException();
            return true;
        }
#if !Portable
		/// <summary>
		/// 转换为新的字符编码
		/// </summary>
		/// <param name="s"></param>
		/// <param name="srcEncoding">当前编码</param>
		/// <param name="dstEncoding">结果编码</param>
		/// <returns></returns>
		[Obsolete( "用ConvertString代替" )]
		public static string ToString( this string s,Encoding srcEncoding ,Encoding dstEncoding )
		{
			return Encoding.Convert(srcEncoding,dstEncoding,s.GetBytes(srcEncoding)).GetString(dstEncoding);
		}

		/// <summary>
		/// 转换为新的字符编码
		/// </summary>
		/// <param name="s"></param>
		/// <param name="srcEncoding">当前编码</param>
		/// <param name="dstEncoding">结果编码</param>
		/// <returns></returns>
		public static string ConvertString( this string s, Encoding srcEncoding, Encoding dstEncoding )
		{
			return Encoding.Convert( srcEncoding, dstEncoding, s.GetBytes( srcEncoding ) ).GetString( dstEncoding );
		}
#endif
		/// <summary>
		/// 通过正则表达式获取匹配的字符串
		/// </summary>
		/// <param name="s"></param>
		/// <param name="pattern">正则表达式</param>
		/// <returns></returns>
        public static string Match(this string s,string pattern)
        {
            Regex rgx = new Regex(pattern);
            if (rgx.IsMatch(s))
            {
                return rgx.Match(s).Value;
            }
            return "";
        }
        public static IEnumerable<string> Matches(this string s, string pattern)
        {
            Regex rgx = new Regex(pattern);
            if (rgx.IsMatch(s))
            {
                var matches = rgx.Matches(s);
                foreach (Match m in matches)
                {
                    yield return m.Value;
                }
            }
        }

        /// <summary>
        /// 通过正则表达式获取匹配的字符串
        /// </summary>
        /// <param name="s"></param>
        /// <param name="pattern">正则表达式</param>
        /// <returns></returns>
        public static string Match(this string s, string pattern,string nameGroup)
        {
            Regex rgx = new Regex(pattern);
            if (rgx.IsMatch(s))
            {
                var match= rgx.Match(s);
                string replace="${"+nameGroup+"}";
                return match.Result(replace);
            }
            return "";
        }
        public static IEnumerable<string> Matches(this string s, string pattern, string nameGroup)
        {
            Regex rgx = new Regex(pattern);
            if (rgx.IsMatch(s))
            {
                var matches = rgx.Matches(s);
                foreach (Match m in matches)
                {
                    string replace = "${" + nameGroup + "}";
                    yield return m.Result(replace);
                }
            }
        }


		/// <summary>
		/// 调用string.Format格式字符串
		/// </summary>
		/// <param name="s"></param>
		/// <param name="p"></param>
		/// <returns></returns>
        public static string Formats(this string s, params object[] p)
        {
            return string.Format(s, p);
        }

		/// <summary>
		/// 转换为uri
		/// </summary>
		/// <param name="s"></param>
		/// <returns></returns>
        public static Uri ToUri(this string s)
        {
            return new Uri(s);
        }



		/// <summary>
		/// 用指定字符串连接字符串数组
		/// </summary>
		/// <param name="ss"></param>
		/// <param name="str"></param>
		/// <returns></returns>
        public static string JoinString(this string[] ss, string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var s in ss)
            {
                sb.Append(s);
                sb.Append(str);
            }
            return sb.ToString().TrimEnd(str.ToCharArray());
        }

		/// <summary>
		/// 根据编码获取字符串对应字节数组
		/// </summary>
		/// <param name="s"></param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public static byte[] GetBytes( this string s, Encoding encoding )
		{
			return encoding.GetBytes( s );
		}
		/// <summary>
		/// 根据编码获取字符串对应字节数组
		/// </summary>
		/// <param name="s"></param>
		/// <param name="encoding"></param>
		/// <returns></returns>
		public static byte[] GetBytes( this string s, string encoding )
		{
			return Encoding.GetEncoding( encoding ).GetBytes( s );
		}
#if !Portable
		/// <summary>
		/// 根据编码获取字符串对应字节数组
		/// </summary>
		/// <param name="s"></param>
		/// <param name="codepage"></param>
		/// <returns></returns>
		public static byte[] GetBytes( this string s, int codepage )
		{
			return Encoding.GetEncoding( codepage ).GetBytes( s );
		}

        /// <summary>
        /// 移除BOM
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string RemoveBOM(this string s)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(s);
            if (bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf)
            {
                string byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
                return s.Remove(0, byteOrderMarkUtf8.Length);
            }
            return s;
        }
#endif
		/// <summary>
		/// 根据指定长度分割字符串
		/// </summary>
		/// <param name="s"></param>
		/// <param name="count">长度</param>
		/// <param name="split">单词分隔符</param>
		/// <returns></returns>
        public static string[] BreakWord(this string s, int count,string split=" ")
        {
            
            List<string> rtn = new List<string>();
            int start = 0;
            while(true)
            {                
                try
                {
                    int pos = s.LastIndexOf(split, count)+1;
                    if (pos <= 0)
                    {
                        rtn.Add(s);
                        break;
                    }
                    string v = s.Substring(start, pos - start);
                    if (v.Trim() == "") continue;
                    rtn.Add(v);
                    s = s.Replace(v, "");
                }
                catch (ArgumentOutOfRangeException)
                {
                    rtn.Add(s);
                    break;
                }       
            }
            return rtn.ToArray();
        }

		/// <summary>
		/// 通过Base64转换获取字节数组
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static byte[] DecodeBase64( this string str )
		{
			return Convert.FromBase64String( str );
		}


		/// <summary>
		/// 解析字符串为16进制数据,字符串形如4fab9b144b的格式
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static IEnumerable<byte> ParseAsHex(this string str)
		{
#if NetFx40
			Contract.Requires( str.Length % 2 == 0, "传入字符串长度必须为偶数" ); 
#endif
			for (int i = 0; i < str.Length; i+=2)
			{
				char c1=str[i];
				char c2=str[i + 1];
				string strHex=new string(new char[]{c1,c2});
				byte b=byte.Parse( strHex, System.Globalization.NumberStyles.HexNumber );
				yield return b;
			}
		}

        public static T ParseTo<T>( this string s ) where T : struct
        {
            var type = typeof( T );
            var parseMethod = type.GetMethod( "Parse", new Type[]{typeof(string)} );
            var o = parseMethod.Invoke( null, new object[] { s } );
            return (T)o;

        }

        public static AsStringObject As(this string str)
        {
            return new AsStringObject(str);
        }


    }

    public class AsStringObject
    {
        string _str;
        public AsStringObject(string str)
        {
            _str=str;
        }
        public Uri Uri()
        {
            return new Uri(_str);
        }

            
    }
}
